/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ListagemCondominios.java
 *
 * Created on Jun 1, 2010, 1:34:17 PM
 */
package adcon.apresentacao;

import adcon.negocio.advogado.Advogado;
import adcon.persistencia.DAO;
import avant.view.AvantViewUtil;
import avant.view.model.AvantTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDesktopPane;

/**
 *
 * @author Administrador
 */
public class TelaListagemAdvogados extends javax.swing.JInternalFrame {

    private AvantTableModel<Advogado> modelo;
    JDesktopPane desktop;
    List<Advogado> advogados;
    DialogoAdvogados tela;

    /** Creates new form ListagemCondominios */
    public TelaListagemAdvogados(JDesktopPane desktop) throws Exception {
        this.desktop = desktop;
        initComponents();
        carregarTabelaCondominio();
        adicionarOuvintes();
    }

    private List carregarTabela() {

        try {
            advogados = new DAO().listar(Advogado.class);
            return advogados;
        } catch (Exception e) {
            e.printStackTrace();
            AvantViewUtil.exibirErro("Não foi possível comunicar com o Banco de Dados!", this);
            return advogados;
        }
    }

    private void editar() {
        if (tbAdvogados.getSelectedRow() >= 0) {
            Advogado advogado = modelo.getObjetoSelecionado();
            tela = new DialogoAdvogados(modelo, null, advogado);
            tela.setVisible(true);
        } else {
            AvantViewUtil.exibirAdvertencia("Você deve selecionar um registro antes de editar!", this);
        }
    }

    private void cancelar(){
        dispose();
    }

    private void adicionar() {
        Advogado advogado = new Advogado();
        tela = new DialogoAdvogados(modelo, null, advogado);
        tela.setVisible(true);
    }

    private void adicionarOuvintes() {
        ControladorDeEventos controlador = new ControladorDeEventos();

        btnAdicionar.addActionListener(controlador);
        btnEditar.addActionListener(controlador);
        btnCancelar.addActionListener(controlador);

        txtPesquisar.addKeyListener(new KeyAdapter() {

            @Override
            public void keyTyped(KeyEvent evt) {
                pesquisar();
            }
        });
        tbAdvogados.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getSource() == tbAdvogados && e.getClickCount() == 2) {
                    editar();
                }
            }
        });

        tbAdvogados.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    editar();
                }
            }
        });
    }

    private void pesquisar() {
        modelo.filtrar();

    }

    private void carregarTabelaCondominio() {
        modelo = new AvantTableModel<Advogado>(tbAdvogados, carregarTabela(), new String[]{"Nome"}) {

            @Override
            public Object getValor(Advogado objeto, int indiceColuna) {
                switch (indiceColuna) {
                    case 0:
                        return objeto.getNome();
//                    case 1:
//                        return objeto.getTelefone1().getNumero();
                    default:
                        throw new RuntimeException("Não foi possível definir o campo do Condominio");
                }
            }

            @Override
            protected List<Advogado> getFiltrar(List<Advogado> advogados) {
                List<Advogado> listaFiltrada = new ArrayList<Advogado>();
                for (Advogado advogado : advogados) {
                    if (advogado.getNome().toLowerCase().contains(txtPesquisar.getText())) {
                        listaFiltrada.add(advogado);
                    }
                }
                if (listaFiltrada.size() > 0) {
                    return listaFiltrada;
                } else {
                    return advogados;
                }
            }
        };
       
    }

    private class ControladorDeEventos implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == btnAdicionar) {
                adicionar();
            } else if (e.getSource() == btnEditar) {
                editar();
            } else if (e.getSource() == btnCancelar){
                cancelar();
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtPesquisar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbAdvogados = new javax.swing.JTable();
        jPanel9 = new javax.swing.JPanel();
        btnAdicionar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Listagem de Advogados");
        setNextFocusableComponent(txtPesquisar);
        setPreferredSize(new java.awt.Dimension(724, 502));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(51, 51, 51), 1, true), "Buscar", javax.swing.border.TitledBorder.RIGHT, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        txtPesquisar.setToolTipText("Digite o que deseja Pesquisar");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tbAdvogados.setFont(new java.awt.Font("Lucida Sans", 0, 12));
        tbAdvogados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbAdvogados.setNextFocusableComponent(btnAdicionar);
        jScrollPane1.setViewportView(tbAdvogados);

        btnAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adcon/imagens/salvar.png"))); // NOI18N
        btnAdicionar.setText("Adicionar");
        btnAdicionar.setToolTipText("Adicionar um novo Condomínio");

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adcon/imagens/editar.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.setToolTipText("Editar um Condomínio");

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adcon/imagens/cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setToolTipText("Adicionar um novo Condomínio");

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGap(117, 117, 117)
                .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(140, Short.MAX_VALUE))
        );

        jPanel9Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdicionar, btnEditar});

        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
                .addContainerGap(11, Short.MAX_VALUE)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdicionar)
                    .addComponent(btnEditar)
                    .addComponent(btnCancelar)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 698, Short.MAX_VALUE)
                    .addComponent(jPanel9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbAdvogados;
    private javax.swing.JTextField txtPesquisar;
    // End of variables declaration//GEN-END:variables
}
